from marshmallow import ValidationError

from exts import db
from mapper import cmaParamsMapper
from flask import Blueprint, jsonify,request
from marshmallowSchema import cmaParamsSchema
bc = Blueprint("api_cmaParams", __name__, url_prefix="/")

# 查询所有cma参数
@bc.route("/queryAll")
def queryAll():
    cma_params_list = cmaParamsMapper.get_cma_params()
    json_list = cmaParamsSchema.dump(cma_params_list)
    return jsonify({"message": "success", "data": json_list, "code": 200})


@bc.route("/queryById")
def queryById():
    key = request.args.get("id")
    print(f'/queryById接口-----------接受arg参数：{key}')
    cma_id = cmaParamsMapper.get_cma_params_by_id(key)
    if cma_id:
        return jsonify({"message": "success", "data": cma_id.to_json(), "code": 200})
    else:
        return jsonify({"message": "查询为空", "code": 201})

# 根据种类查询cma参数
@bc.route("/queryByCategory", methods=["GET"])
def queryByCategory():
    key = request.args.get("category")
    print(f'/queryByCategory接口-----------接受arg参数：{key}')
    cma_params_list = cmaParamsMapper.get_cma_params_by_category("水")
    if cma_params_list:
        cma_json_list = [param.to_json() for param in cma_params_list]  # 将每个实例转换为JSON
        return jsonify({"message": "success", "data": cma_json_list, "code": 200})
    else:
        print("查询为空")
        return jsonify({"message": "查询为空", "code": 201})

# 根据种类、项目名查询cma
@bc.route("/queryByParams", methods=["GET"])
def queryByParams():
    key = request.args.get("category")
    key2 = request.args.get("parameterName")
    key3 = request.args.get("standardMethod")
    print(f'/queryByCategoryOrParameterName接口-----------接受arg参数：{key},{key2},{key3}')
    cma_params_list = cmaParamsMapper.get_cma_params_by_category_and_parameterName(category=key, parameterName=key2, standardMethod=key3)
    if cma_params_list:
        cma_json_list = [param.to_json() for param in cma_params_list]  # 将每个实例转换为JSON
        return jsonify({"message": "success", "data": cma_json_list, "code": 200})


# 添加中国计量参数
@bc.route("/addCmaParams", methods=["POST"])
def addCmaParams():
    data = request.get_json()
    print(f'/addCmaParams接口-----------接受数据参数：{data}')
    try:
        cma_params = cmaParamsSchema.load(data,session=db.session)  #  然后用实例调用 load()
        print(cma_params.to_json())
        print(cmaParamsSchema.dump(cma_params))
        return jsonify({"message": "成功", "code": 200})
    except ValidationError as err:
        return jsonify({"errors": err.messages}) # 返回错误信息